// 更新用户信息接口
export default defineEventHandler(async (event) => {
  const authHeader = getHeader(event, 'authorization')
  const body = await readBody(event)
  
  // 模拟延迟
  await new Promise(resolve => setTimeout(resolve, 500))

  // 验证 token
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    throw createError({
      statusCode: 401,
      message: '未登录或 token 无效'
    })
  }

  const token = authHeader.substring(7)

  if (!token.startsWith('token_')) {
    throw createError({
      statusCode: 401,
      message: 'token 格式错误'
    })
  }

  // 从 token 中提取用户ID
  const parts = token.split('_')
  const userId = parts[1]

  if (!userId) {
    throw createError({
      statusCode: 401,
      message: 'token 格式错误'
    })
  }

  // 允许更新的字段
  const allowedFields = ['username', 'bio', 'phone', 'avatar']
  const updates: Record<string, any> = {}
  
  for (const field of allowedFields) {
    if (body[field] !== undefined) {
      updates[field] = body[field]
    }
  }

  // 模拟更新后的用户数据
  const updatedUser = {
    id: userId,
    email: userId === '1' ? 'admin@example.com' : 'test@example.com',
    role: userId === '1' ? 'admin' : 'user',
    createdAt: '2024-01-01T00:00:00.000Z',
    ...updates
  }

  return {
    code: 200,
    message: '更新成功',
    data: updatedUser
  }
})

